﻿using System.Diagnostics.CodeAnalysis;
using System.Linq;
using CultivationSkills.Utils;
using ThunderRoad;
using UnityEngine;

namespace CultivationSkills.Skills;

[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")]
[SuppressMessage("ReSharper", "FieldCanBeMadeReadOnly.Global")]
[SuppressMessage("ReSharper", "ConvertToConstant.Global")]
public class PreciseThrow : MonoBehaviour
{
    public static ModOptionInt[] ForceOptions = ModOptionInt.CreateArray(20, 500, 5);
    [ModOption(name = "Enabled", order = 3, category = "Precise Throw")]
    public static bool PreciseThrowEnabled = true;

    [ModOption(name = "Force", order = 7,
        interactionType = ModOption.InteractionType.Slider, category = "Precise Throw",
        valueSourceName = "ForceOptions", saveValue = true)]
    public static int Force = 50;

    [ModOption(name = "Source", order = 7, tooltip = "Check Ray Source Location",
        interactionType = ModOption.InteractionType.Slider, category = "Precise Throw", saveValue = true)]
    public static SourceEnum Source = SourceEnum.Player;

    public enum SourceEnum
    {
        Player,
        Item
    }

    public Item item;
    private Rigidbody _rigidbody;

    private void Start()
    {
        if (!item)
        {
            return;
        }

        _rigidbody = item.GetComponent<Rigidbody>();
        if (_rigidbody == null)
        {
            Debug.LogError(this.name + ": No rigidbody attached");
            return;
        }

        item.OnThrowEvent += i =>
        {
            if (PlayerControl.GetHand(Side.Right).usePressed)
            {
                AutoNavRun();
            }
        };
        // item.OnFlyStartEvent += i => AutoNavRun();
        item.OnFlyEndEvent += i => FlyEnd();
    }

    public void FlyEnd()
    {
    }


    public void AutoNavRun()
    {
        if (!PreciseThrowEnabled || !Player.local)
        {
            return;
        }

        if (!GameUtils.FindForwardHitNpc(GetSourceTransform(), out var hit))
        {
            Debug.Log("未发现敌人！");
            return;
        }

        Debug.Log("发现" + hit.collider.gameObject);
        var pi = hit.collider.gameObject.GetComponentInParent<Item>();
        Debug.Log("hit item:" + (pi == null));
        // 计算击中位置和玩家位置之间的向量
        var throwDirection = hit.point - item.transform.position;
        // 归一化这个向量
        throwDirection.Normalize();
        Debug.Log("throwDirection: " + throwDirection);
        Debug.Log("Target:" + hit.point);
        // 施加力，这里你可以根据需要调整力的大小
        _rigidbody.AddForce(throwDirection * Force, ForceMode.Impulse);
    }

    private Transform GetSourceTransform()
    {
        if (Source == SourceEnum.Player)
        {
            return Player.local.head.transform;
        }

        return item.flyDirRef != null ? item.flyDirRef.transform : item.transform;
    }

    public static void ImbueSkill()
    {
        Init();
        var list = GameUtils.ImbueCommentToHandleItem<PreciseThrow>();
        if (list.IsNullOrEmpty())
        {
            return;
        }

        foreach (var preciseThrow in list.Where(preciseThrow => preciseThrow.item == null))
        {
            preciseThrow.item = preciseThrow.GetComponent<Item>();
            preciseThrow.Start();
        }
    }

    private static bool _initialized = false;

    private static void Init()
    {
        if (_initialized)
        {
            return;
        }

        EventManager.OnItemRelease += (handle, ragdollHand, throwing) =>
        {
            Debug.Log("OnItemRelease:" + handle.name + ";throwing:" + throwing);
        };
        _initialized = true;
    }
}